package cn.windy.samary.module.admin.service.impl;

import cn.windy.samary.module.admin.common.Tree;
import cn.windy.samary.module.admin.entity.Dept;
import cn.windy.samary.module.admin.mapper.DeptMapper;
import cn.windy.samary.module.admin.service.IDeptService;
import cn.windy.samary.module.abstracts.service.impl.AbstractServiceImpl;
import cn.windy.samary.utils.BuildTree;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zyl
 * @date 2018-05-26 16:07
 */
@Service
public class DeptServiceImpl extends AbstractServiceImpl<Dept> implements IDeptService {

    @Resource
    private DeptMapper deptMapper;

    @Override
    public Tree<Dept> getTree() {
        List<Tree<Dept>> trees = new ArrayList<Tree<Dept>>();
        List<Dept> sysDepts = deptMapper.selectAll();

        for (Dept dept : sysDepts) {
            Tree<Dept> tree = new Tree<Dept>();
            tree.setId(dept.getId());
            tree.setParentId(dept.getpId());
            tree.setText(dept.getName());
            Map<String, Object> state = new HashMap<>(16);
            state.put("opened", true);
            tree.setState(state);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        Tree<Dept> t = BuildTree.build(trees);
        return t;
    }

    /**
     * 判断deptId 是否pId的子或者本身，在更改部门的父级部门时使用
     *
     * @param deptId deptId
     * @param pId    pId
     * @return
     */
    @Override
    public boolean isChild(String deptId, String pId) {
        if (deptId.equals(pId)) {
            return true;
        }
        List<Dept> list = findAllChild(deptId);
        for (Dept dept : list) {
            if (pId.equals(dept.getId())) {
                return true;
            }
        }
        return false;
    }

    private List<Dept> findAllChild(String deptId) {
        List<Dept> list = new ArrayList<>();
        findChild(deptId, list);
        return list;
    }

    private void findChild(String deptId, List<Dept> list) {
        List<Dept> byPId = deptMapper.findByPId(deptId);
        list.addAll(byPId);
        for (Dept dept : byPId) {
            findChild(dept.getId(), list);
        }

    }
}
